﻿/* $RCSFile: CRMAddImage.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageManager/PageModules/CRMAddImage/CRMAddImage.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:56:46  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 7 2010/08/09 09:44:01  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using CrmSdk;
using CrmSdk.CRM4;

using AddonNice.CRMImage;
using AddonNice.Settings.CRMImage;
using AddonNice.CRMImage.UI.WebControls;

using AddonNice.CRMWrapper.CRMImage;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;


namespace AddonNice.PageModules.CRMAddImage
{
    public partial class CRMAddImage : PortalCrmImageModuleControl
    {

        #region Global implementation

		/// <summary>
		/// Only 4
		/// </summary>
		public override VersionType ModuleType
		{
			get
			{
				return VersionType.CrmV4;
			}
		}

        public override bool AdminModule
        {
            get
            {
                return true;
            }
        }

        public override Guid GuidID
        {
            get
            {
                return new Guid(ImStr.CRMAddImageGuid);;
            }
        }

        #endregion Global implementation

        ArrayList _AllEntities =   null;
        ArrayList GetAllEntities(bool useAll)
        {
            if (_AllEntities == null)
            {
                _AllEntities          =   MetadataCache.GetAllEntities(Wrapper,useAll);
            }
            return _AllEntities;
        }
        

        string StrNewTab        =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_NEWTAB","New Tab");
        string StrNewSection    =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_NEWSECTION","New Section");

        /// <summary>
        /// CTor installs validation group 'Main'
        /// </summary>
        public CRMAddImage()
        {
            ValidationGroup                     =   "Main";
            //const string extgrp                 =   "CRMADDIMAGE";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage Page_Load BEG IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
   			// If first visit to the page, update all entries
			if ( !IsPostBack ) 
			{
                // Load available image modules
                BindComboModules();
                // Load entities
                ArrayList are                               =   GetAllEntities(true);
                RadComboEntities.DataTextField              =   "displayName";
                RadComboEntities.DataValueField             =   "entityName";
                RadComboEntities.Sort                       =   RadComboBoxSort.Ascending;
                RadComboEntities.SortCaseSensitive          =   false;
                RadComboEntities.DataSource                 =   are;
                DataBind();
                RadComboEntities.DataBind();
                RadComboEntities.SortItems();
			}
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage Page_Load END IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// Establish a list of potential CRMImage modules to share settings with
        /// </summary>
        void BindComboModules()
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CRMAddImage BindComboModules BEG.",PageTraceSwitch.Sw.Info);
            ModulesDB mdb               =   new ModulesDB();
            Guid exguid                 =   new Guid(ImStr.CRMImageGuid);
            try
            {
                ArrayList lst           =   mdb.FindModulesByGuid(portalSettings.PortalID, exguid,ModuleID);
                ModuleItem mi           =   new ModuleItem();
                mi.Title                =   "No Module";
                mi.ID                   =   0;
                lst.Insert(0, mi);
                ComboModules.DataTextField = "Title";
                ComboModules.DataValueField = "ID";
                ComboModules.DataSource = lst;
                ComboModules.DataBind();
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMAddImage BindComboModules ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CRMAddImage BindComboModules END.",PageTraceSwitch.Sw.Info);
        }

        private void FindSectionsInTab(string TabId,NodeUtil ndu,bool add)
        {
            for (int i = 0; i < ndu.Nodes.Count; i++)
            {
                NodeUtil nu     =   ndu.Nodes[i];
                RadTreeNode nd  =   new RadTreeNode(nu.Text);
                if (nu.Type == NodeType.Section && add)
                {
                    string scName = nu.Text.Replace("Section '", string.Empty).Trim(new char[] { '\'' });
                    RadComboSection.Items.Add(new RadComboBoxItem(scName,ndu.Id));
                }
                if (nu.Type == NodeType.Tab && TabId == nu.Id)
                {
                    add         =   true;
                    FindSectionsInTab(TabId, nu, add);
                    add         =   false;
                    return;
                }
                FindSectionsInTab(TabId, nu, add);
            }
        }

        void FillTreeView(TreeUtil fTree)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage FillTreeView BEG fTree: {0}",fTree.Node.Text),ModuleTraceSwitch.Sw.Info);
            RadFormTree.UnselectAllNodes();
            RadFormTree.Nodes.Clear();
            RadTreeNode nd0         =   new RadTreeNode(fTree.Node.Text,fTree.Node.Id);
            RadFormTree.Nodes.Add(nd0);
            nd0.Expanded            =   true;
            
            RadComboTab.ClearSelection();
            RadComboTab.Items.Clear();
            RadComboBoxItem it0     =   new RadComboBoxItem(StrNewTab,string.Empty);
            RadComboTab.Items.Add(it0);
            it0.Selected            =   true;

            RadComboSection.ClearSelection();
            RadComboSection.Items.Clear();
            it0                     =   new RadComboBoxItem(StrNewSection,string.Empty);
            RadComboSection.Items.Add(it0);
            it0.Selected            =   true;
            FillNodes(nd0,fTree.Node);
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage FillTreeView END Nodes.Count: {0}",RadFormTree.Nodes.Count),ModuleTraceSwitch.Sw.Info);
        }

        private void FillNodes(RadTreeNode nd0, NodeUtil ndu)
        {
            for (int i = 0; i < ndu.Nodes.Count; i++)
            {
                NodeUtil nu         =   ndu.Nodes[i];
                RadTreeNode nd      =   new RadTreeNode(nu.Text,nu.Id);
                if (nu.Type == NodeType.Tab)
                {
                    string tbName   =   nu.Text.Replace("Tab '",string.Empty).Trim(new char[]{'\''});
                    RadComboTab.Items.Add(new RadComboBoxItem(tbName,nu.Id));
                }
                nd0.Nodes.Add(nd);
                if ( nu.Type == NodeType.Form ||
                     nu.Type == NodeType.Tab
                    )
                    nd.Expanded     =   true;
                FillNodes(nd, nu);

            }
        }
        
        /// <summary>
        /// We export corresponding entity from CRM and build treeview with its data
        /// Also fill the Combo of Tabs and Sections (must be dynamic)
        /// </summary>
        void FillTree()
        {
            string selectedEntity   =   RadComboEntities.SelectedValue;
            CrmUtil4Form util       =   new CrmUtil4Form((CrmWrapper4)Wrapper,selectedEntity);
            util.ExportXml();
            TreeUtil fTree          =   util.BuildTree(true,true);
            FillTreeView(fTree);
        }

        void FillSummary(bool init)
        {
            StringBuilder sb    =   new StringBuilder();
            string fmt          =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_SUMMARYFMT1","Entity : {0}{1}");
            sb.AppendFormat(fmt, RadComboEntities.Text,StStr.strBr);
            fmt                 =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_SUMMARYFMT3","Tab : {0}{1}");
            sb.AppendFormat(fmt, RadComboTab.Text,StStr.strBr);
            fmt                 =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_SUMMARYFMT4","Section : {0}{1}");
            sb.AppendFormat(fmt, RadComboSection.Text,StStr.strBr);
            fmt                 =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_SUMMARYFMT6","Click on Update Button to proceed.");
            Literal lit         =   new Literal();
            lit.Text            =   sb.ToString();
            PnSummary.Controls.Add(lit);
        }

        void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage RadTabStrip1_TabClick  BEG TabIndex: {0}.", e.Tab.TabIndex), ModuleTraceSwitch.Sw.Info);
            // We go back in expert
            if (RadTabStrip1.SelectedTab.Index > e.Tab.Index)
                return;
            switch (e.Tab.TabIndex)
            {
                case 2:
                    FillTree();
                    return;
                case 3:
                    FillSummary(true);
                    return;
            }
        }

        void RadComboTab_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string selTab               =   string.Format("Tab '{0}'",RadComboTab.SelectedItem.Text);
            RadComboSection.ClearSelection();
            RadComboSection.Items.Clear();
            RadComboBoxItem it0         =   new RadComboBoxItem(StrNewSection,string.Empty);
            RadComboSection.Items.Add(it0);
            it0.Selected                =   true;
            if (selTab != StrNewTab)
            {
                string selectedEntity   =   RadComboEntities.SelectedValue;
                CrmUtil4Form util       =   new CrmUtil4Form((CrmWrapper4)Wrapper, selectedEntity);
                util.ExportXml();
                TreeUtil fTree          =   util.BuildTree(true, true);
                FindSectionsInTab(selTab, fTree.Node, false);
            }
        }
        /// <summary>
        /// Use EntityBuilder to Build entity
        /// </summary>
        void CRMAddImage_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if (!Page.IsValid || ( ComboModules.SelectedIndex == -1 ) )
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]CRMAddImage CRMAddImage_ADNUpdateModule : Page not valid",ModuleTraceSwitch.Sw.Info);
                e.Cancel            =   true;
                return;
            }
            try
            {
                string entDisplayName   =   RadComboEntities.Text;
                string entName          =   RadComboEntities.SelectedValue;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage CRMAddImage_ADNUpdateModule BEG Build Entity: {0}",entName),ModuleTraceSwitch.Sw.Info);
                // We create a new Page for the Iframe and insert inside a CrmImageBook module
                // This page will be created under the dedicated page for Iframes
                PagesDB pagesDB         =   new PagesDB();
                int IFramePageId        =   portalSettings.CustomSettings[ImStr.IFramePageMenu].ToInt();
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage CRMAddImage_ADNUpdateModule IFramePageId: {0}",IFramePageId),ModuleTraceSwitch.Sw.Info);
                int wPageId             =   pagesDB.AddPage(portalSettings.PortalID, IFramePageId,
                    string.Format("IFrame for {0}",entDisplayName),
                    StStr.strDefaultSkin, 10,3,0,0,0,0,0,DBAllUser);
                // Add module
                ModulesDB modDB			=	new ModulesDB();
                int moduleDefId         =   modDB.GetModuleDefinitionByGuid(StStr.DefaultPortalID,new Guid(ImStr.CRMImageBookGuid));
                int modId               =   modDB.AddModule(wPageId,1,0,StStr.contentPane,
                    string.Format("Image Book for {0}",entDisplayName),
                    moduleDefId, 0,DBAdmin2, DBAllUser2,DBAdmin2, DBAdmin2,DBAdmin2, DBAdmin2,DBAdmin2, false, false);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage CRMAddImage_ADNUpdateModule created moduleDefId: {0}, ModuleID: {1}.", 
                            moduleDefId,modId), ModuleTraceSwitch.Sw.Info);
                // Makes ImageBook module share settings with CrmImage modules 
                modDB.UpdateModuleSettingsID(modId,int.Parse(ComboModules.SelectedValue));
                string TabName          =   RadComboTab.Text;
                string SectionName      =   RadComboSection.Text;
                string TabId            =   RadComboTab.SelectedValue;
                string SectionId        =   RadComboSection.SelectedValue;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage CRMAddImage_ADNUpdateModule PageId: {0}, Tab: {1}, Section: {2}, ,TabId: {3}, SectionId: {4}",
                                            new object[]{wPageId,TabName,SectionName,TabId,SectionId}),ModuleTraceSwitch.Sw.Info);
                string url              =   HttpUrlBuilder.BuildUrlWithCustomAttributes(wPageId,string.Format("{0}=1",CrmStr.strCrmMark));
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage CRMAddImage_ADNUpdateModule Url: {0}",url),ModuleTraceSwitch.Sw.Info);
                CrmUtil4Form util       =   new CrmUtil4Form((CrmWrapper4)Wrapper, entName);
                util.entityDisplayName  =   entDisplayName;
                bool ret                =   false;
                if ( TabName    == StrNewTab )
                        ret             =   util.AddNewIframe(url,true);
                else if ( SectionName == StrNewSection )
                        ret             =   util.AddNewIframe(TabId,url,true);
                else    ret             =   util.AddNewIframe(TabId,SectionId,url,true);
                if (ret)
                {
                    FillSummary(false);
                    StringBuilder sb    =   new StringBuilder();
                    sb.AppendFormat("LCID : {0}{1}{1}", util.LCID,StStr.strBr);
                    string fmt          =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_SUCCESSMSGFMT1","IFrame successfully Created in Tab: {0}, Section: {1}, Control: {2}.<br />");
                    sb.AppendFormat(fmt,util.iFrameTabName,util.iFrameSectionName,util.iFrameName);
                    fmt                 =   LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"CRMADDIMAGE_SUCCESSMSGFMT2","Entity {0} published.");
                    sb.AppendFormat(fmt,entDisplayName);
                    Literal lit         =   new Literal();
                    lit.Text            =   sb.ToString();
                    PnSummary.Controls.Add(lit);
                    // invalidate update button
                    updateBtn.Enabled   =   false;
                }
                else
                {
                    StringBuilder sb    =   new StringBuilder();
                    sb.AppendFormat("Error creating IFrame : {0}","");
                    Literal lit         =   new Literal();
                    lit.Text            =   sb.ToString();
                    PnSummary.Controls.Add(lit);
                }
            }
            catch (SoapException sex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMAddImage CRMAddImage_ADNUpdateModule soap ex :{0}", sex), ModuleTraceSwitch.Sw.Info);
                StringBuilder sb        =   new StringBuilder();
                sb.AppendFormat("Error: <br />{0}<br />",ErrorCodes.GetErrorMessage(sex));
                PnSummary.Controls.Add(new LiteralControl(sb.ToString()));
                e.Cancel                =   true;
                return;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMAddImage CRMAddImage_ADNUpdateModule ex :{0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }
 
        /// <summary>
        /// Reset all values
        /// </summary>
        void ResetBtn_Click(object sender, ImageClickEventArgs e)
        {
            PnSummary.Controls.Clear();
			RadTab Tab                  =   RadTabStrip1.Tabs[0];
			Tab.Enabled                 =   true;
			Tab.Selected                =   true;
            RadPageView PageView        =   RadMultiPage1.PageViews[0];
			PageView.Selected           =   true;
			Tab                         =   RadTabStrip1.Tabs[1];
			Tab.Enabled                 =   false;
			Tab                         =   RadTabStrip1.Tabs[2];
			Tab.Enabled                 =   false;
            
            RadFormTree.UnselectAllNodes();
            RadFormTree.Nodes.Clear();
            
            RadComboTab.ClearSelection();
            RadComboTab.Items.Clear();
            RadComboSection.ClearSelection();
            RadComboSection.Items.Clear();
            
            updateBtn.Enabled           =   true;
        }

        void BtnNext_Click(object sender, ImageClickEventArgs e)
        {
            int idx                 =   RadTabStrip1.SelectedIndex;
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage BtnNext_Click  BEG TabIndex: {0}.",idx),ModuleTraceSwitch.Sw.Info);
			RadTab Tab              =   RadTabStrip1.Tabs[idx+1];
			Tab.Enabled             =   true;
			Tab.Selected            =   true;
            RadPageView PageView    =   RadMultiPage1.PageViews[idx+1];
			PageView.Selected       =   true;
            if ( idx == 0 )
                FillTree();
            else if ( idx == 1)
                FillSummary(true);
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMAddImage BtnNext_Click  END New Tab Index: {0}.",Tab.Index),ModuleTraceSwitch.Sw.Info);
		}

        #region Std Overrides
        
        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Update_" + strcult;
            ResetBtn.SkinID     =   "Reset_" + strcult;
            BtnNext.SkinID      =   "setupnext_" + strcult;
            BtnNext2.SkinID     =   "setupnext_" + strcult;
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                                +=  new System.EventHandler(Page_Load);
            ADNUpdateModule                     +=  new PortalModuleEventHandler(CRMAddImage_ADNUpdateModule);
            ResetBtn.Click                      +=  new ImageClickEventHandler(ResetBtn_Click);
            RadTabStrip1.TabClick               +=  new RadTabStripEventHandler(RadTabStrip1_TabClick);
            BtnNext.Click                       +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext2.Click                      +=  new ImageClickEventHandler(BtnNext_Click);
            RadComboTab.SelectedIndexChanged    += new RadComboBoxSelectedIndexChangedEventHandler(RadComboTab_SelectedIndexChanged);
        }

        #endregion
    }
}